package com.doumuxie.config;

import com.doumuxie.exception.RunErrorException;
import com.doumuxie.util.ResultUtil;
import com.doumuxie.util.SysCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author liangliang
 * @version 1.0
 * @date 2019/5/28 11:17
 * @description GlobalExceptionHandler 全局异常处理
 **/
@ControllerAdvice
public class GlobalExceptionHandlerConfig {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandlerConfig.class);

    /**
     * 捕获全局异常
     *
     * @param e 异常信息
     * @return 返回统一格式
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultUtil exceptionHandler(Exception e) {
        logger.error("业务出现异常", e);
        return ResultUtil.error(SysCode.SERVER_BUSY);
    }

    /**
     * 捕获 HttpRequestMethodNotSupportedException 异常
     *
     * @param e 异常信息
     * @return 返回 错误的请求方式
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public ResultUtil noSuchMethodHandler(HttpRequestMethodNotSupportedException e) {
        logger.error("=============错误的请求方式===============");
        return ResultUtil.error(SysCode.REQUEST_METHOD_NOT_SUPPORT);
    }


    /**
     * 捕获 自定义 异常
     *
     * @param e 异常信息
     * @return 返回 错误的请求方式
     */
    @ExceptionHandler(RunErrorException.class)
    @ResponseBody
    public ResultUtil runErrorExceptionHandler(RunErrorException e) {
        return ResultUtil.error(e.getMessage());
    }

}
